package com.myrpc.handler;

import java.util.List;

import com.myrpc.utils.SerializationUtil;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

/**
 * Created with IntelliJ IDEA.
 *
 * @Description:
 * @User: weiyi.liu
 * @Date: 2018-06-08
 * @Time: 16:56
 */
public class RpcDecoder extends ByteToMessageDecoder {

	private Class<?> genericClass;

	public RpcDecoder(Class<?> genericClass) {
		this.genericClass = genericClass;
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> list) throws Exception {
		if (byteBuf.readableBytes() < 4) {
			return;
		}
		//byteBuf.markReaderIndex();
		int dataLength = byteBuf.readInt();
		if (dataLength <= 0) {
			ctx.close();
		}
		if (byteBuf.readableBytes() < dataLength) {
			//byteBuf.resetReaderIndex();
			ctx.close();
		}
		byte[] data = new byte[dataLength];
		byteBuf.readBytes(data);

		Object obj = SerializationUtil.deserialize(data, genericClass);
		list.add(obj);
	}
}
